import React, { useEffect, useRef, useState } from 'react';
import { GestureRecognizer, FilesetResolver, DrawingUtils } from '@mediapipe/tasks-vision';

interface GestureInfo {
    categoryName: string;
    categoryScore: string;
    handedness: string;
}

// 手势枚举
const enumGesture: { [key: string]: string } = {
    Closed_Fist: '握紧拳头',
    Open_Palm: '张开手掌',
    Thumb_Up: '竖起大拇指',
    Thumb_Down: '拇指朝下',
    Pointing_Up: '指向上',
    Pointing_Down: '指向下', // 添加指向下手势支持
    Victory: '剪刀',
    None: '未识别',
};

const GestureRecognizerComponent: React.FC = () => {
    const videoRef = useRef<HTMLVideoElement>(null);
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const gestureRecognizerRef = useRef<GestureRecognizer | null>(null);
    const [runningMode, setRunningMode] = useState<string | null>(null);
    const [videoGestureInfo, setVideoGestureInfo] = useState<GestureInfo>({
        categoryName: '',
        categoryScore: '',
        handedness: '',
    });
    const [debugInfo, setDebugInfo] = useState<string>('初始化中...'); // 添加调试信息
    const lastTriggerTime = useRef<number>(0);
    const DEBOUNCE_DELAY = 1000;


    // --------------------------
    // 1. 手势事件处理函数
    // --------------------------
    const handleThumbUp = () => {
        console.log('触发【提交】操作');
        alert('检测到“竖起大拇指”，执行提交！');
    };

    const handleVictory = () => {
        console.log('触发【重置】操作');
        alert('检测到“剪刀手势”，执行重置！');
    };

    const handleClosedFist = () => {
        console.log('触发【关闭】操作');
        alert('检测到“握紧拳头”，执行关闭！');
    };

    // 修复：指向上 -> 上滚一屏
    const handlePointingUp = () => {
        console.log('触发【向上翻页】操作');
        setDebugInfo('执行向上翻页');
        
        const screenHeight = window.innerHeight;
        const currentScrollY = window.scrollY;
        // 向上滚动应该是减去屏幕高度
        const targetScrollY = Math.max(0, currentScrollY - screenHeight);
        
        window.scrollTo({
            top: targetScrollY,
            behavior: 'smooth'
        });
    };

    // 新增：指向下 -> 下滚一屏
    const handlePointingDown = () => {
        console.log('触发【向下翻页】操作');
        setDebugInfo('执行向下翻页');
        
        const screenHeight = window.innerHeight;
        const currentScrollY = window.scrollY;
        const documentHeight = document.documentElement.scrollHeight;
        // 向下滚动并防止超出页面底部
        const targetScrollY = Math.min(
            currentScrollY + screenHeight,
            documentHeight - screenHeight
        );
        
        window.scrollTo({
            top: targetScrollY,
            behavior: 'smooth'
        });
    };

    // --------------------------
    // 2. 手势监听与事件触发
    // --------------------------
    useEffect(() => {
        const confidenceThreshold = 80;
        const currentScore = parseFloat(videoGestureInfo.categoryScore);
        const currentGesture = videoGestureInfo.categoryName;

        // 更新调试信息
        setDebugInfo(`识别到: ${currentGesture} (置信度: ${currentScore}%)`);

        if (currentGesture && currentScore >= confidenceThreshold) {
            const now = Date.now();
            if (now - lastTriggerTime.current < DEBOUNCE_DELAY) {
                setDebugInfo(`防抖中: ${currentGesture}`);
                return;
            }
            lastTriggerTime.current = now;

            // 修正手势匹配逻辑
            switch (currentGesture) {
                case enumGesture.Thumb_Up:
                    handleThumbUp();
                    break;
                case enumGesture.Victory:
                    handleVictory();
                    break;
                case enumGesture.Closed_Fist:
                    handleClosedFist();
                    break;
                case enumGesture.Pointing_Up:
                    handlePointingUp();
                    break;
                case enumGesture.Pointing_Down:  // 添加指向下手势处理
                    handlePointingDown();
                    break;
                default:
                    setDebugInfo(`未处理的手势: ${currentGesture}`);
                    break;
            }
        }
    }, [videoGestureInfo]);


    // 判断是否可以使用摄像头
    const hasGetUserMedia = () => !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);

    // 创建手势识别器（修复资源加载问题）
    const createGestureRecognizer = async () => {
        try {
            setDebugInfo('开始加载WASM资源...');
            // 修复WASM加载路径
            const vision = await FilesetResolver.forVisionTasks(
                'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.3/wasm/vision_wasm_internal.js'
            );

            setDebugInfo('开始加载模型...');
            // 修复模型路径，使用官方CDN
            gestureRecognizerRef.current = await GestureRecognizer.createFromOptions(vision, {
                baseOptions: {
                    modelAssetPath: 'https://storage.googleapis.com/mediapipe-models/gesture_recognizer/gesture_recognizer/float16/1/gesture_recognizer.task',
                    delegate: 'CPU', // 改用CPU提高兼容性
                },
                numHands: 2,
            });

            setDebugInfo('手势识别器加载完毕');
            predictWebcam();
        } catch (error) {
            const errorMsg = `加载失败: ${(error as Error).message}`;
            console.error(errorMsg, error);
            setDebugInfo(errorMsg);
            alert(errorMsg);
        }
    };

    // 识别视频中的手势
    const predictWebcam = async () => {
        if (!hasGetUserMedia()) {
            setDebugInfo('不支持摄像头访问');
            return alert('此设备不支持摄像头访问!');
        }

        const video = videoRef.current;
        const canvasElement = canvasRef.current;

        if (!video || !canvasElement || !gestureRecognizerRef.current) {
            setDebugInfo('元素未正确初始化');
            return alert('视频或画布元素未正确初始化');
        }

        if (runningMode !== 'VIDEO') {
            setRunningMode('VIDEO');
            await gestureRecognizerRef.current.setOptions({ runningMode: 'VIDEO' });
        }
        await gestureRecognizerRef.current.setOptions({ numHands: 2 });

        // 同步Canvas尺寸与视频尺寸
        const setCanvasDimensions = () => {
            if (video && canvasElement) {
                canvasElement.width = video.videoWidth || 640;
                canvasElement.height = video.videoHeight || 480;
            }
        };

        video.addEventListener('loadedmetadata', setCanvasDimensions);
        window.addEventListener('resize', setCanvasDimensions);
        setCanvasDimensions();

        const canvasCtx = canvasElement.getContext('2d');
        if (!canvasCtx) {
            setDebugInfo('无法获取Canvas上下文');
            return;
        }

        let lastVideoTime = -1;
        setDebugInfo('开始处理视频帧');

        const processVideoFrame = () => {
            if (!video || !gestureRecognizerRef.current) return;

            const nowInMs = Date.now();
            let results: any = {};
            if (video.currentTime !== lastVideoTime) {
                lastVideoTime = video.currentTime;
                try {
                    results = gestureRecognizerRef.current.recognizeForVideo(video, nowInMs);
                } catch (error) {
                    setDebugInfo(`帧处理错误: ${(error as Error).message}`);
                    console.error('处理视频帧时出错:', error);
                }
            }

            // 绘制逻辑
            canvasCtx.save();
            canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height);
            canvasCtx.scale(-1, 1);
            canvasCtx.translate(-canvasElement.width, 0);

            const drawingUtils = new DrawingUtils(canvasCtx);
            if (results.landmarks) {
                for (const landmarks of results.landmarks) {
                    drawingUtils.drawConnectors(landmarks, GestureRecognizer.HAND_CONNECTIONS, {
                        color: '#00FF00',
                        lineWidth: 3,
                    });
                    drawingUtils.drawLandmarks(landmarks, {
                        color: '#FF0000',
                        radius: 2.5,
                    });
                }
            }

            canvasCtx.restore();

            // 处理识别结果
            if (results?.gestures?.length > 0) {
                const originalHandedness = results.handednesses[0][0]?.displayName || '';
                const correctedHandedness = originalHandedness === 'Left' ? 'Right' : 'Left';
                const gestureName = results.gestures[0][0].categoryName;

                setVideoGestureInfo({
                    categoryName: enumGesture[gestureName] || gestureName,
                    categoryScore: (results.gestures[0][0].score * 100).toFixed(2),
                    handedness: correctedHandedness,
                });
            } else {
                setVideoGestureInfo({
                    categoryName: '',
                    categoryScore: '',
                    handedness: '',
                });
            }

            requestAnimationFrame(processVideoFrame);
        };

        // 启动摄像头
        try {
            setDebugInfo('请求摄像头权限...');
            const stream = await navigator.mediaDevices.getUserMedia({
                video: { 
                    width: { ideal: 640 }, 
                    height: { ideal: 480 },
                    facingMode: 'user' // 明确使用前置摄像头
                } 
            });
            
            if (video) {
                video.srcObject = stream;
                video.addEventListener('loadeddata', processVideoFrame);
                setDebugInfo('摄像头启动成功');
            }
        } catch (err) {
            const errorMsg = `摄像头访问失败: ${(err as Error).message}`;
            console.error(errorMsg, err);
            setDebugInfo(errorMsg);
            alert(errorMsg);
        }
    };

    // 组件挂载时初始化
    useEffect(() => {
        createGestureRecognizer();

        return () => {
            if (gestureRecognizerRef.current) {
                gestureRecognizerRef.current.close();
            }
            const video = videoRef.current;
            if (video && video.srcObject) {
                (video.srcObject as MediaStream).getTracks().forEach(track => track.stop());
                video.srcObject = null;
            }
        };
    }, []);

    return (
        <div className="gesture-recognition-container">
            {/* 调试信息显示 */}
            <div style={{ padding: '10px', background: '#f0f0f0', marginBottom: '10px' }}>
                调试: {debugInfo}
            </div>
            
            <div className="video-container" style={{ position: 'relative' }}>
                <video
                    ref={videoRef}
                    autoPlay
                    muted
                    playsInline
                    style={{ opacity: 0, position: 'absolute' }}
                />
                <canvas
                    ref={canvasRef}
                    style={{ border: '1px solid #000', maxWidth: '100%' }}
                />
            </div>

            {/* 识别结果 */}
            {videoGestureInfo.categoryName && (
                <div className="gesture-info" style={{ marginTop: 10, padding: '10px' }}>
                    <div>识别手势: {videoGestureInfo.categoryName}</div>
                    <div>置信度: {videoGestureInfo.categoryScore}%</div>
                    <div>手: {videoGestureInfo.handedness}</div>
                </div>
            )}

            {/* 手势说明 */}
            <div style={{ marginTop: 20, fontSize: '0.9em', color: '#666' }}>
                <p>支持的手势操作:</p>
                <ul>
                    <li>指向上: 向上滚动一屏</li>
                    <li>指向下: 向下滚动一屏</li>
                    <li>竖起大拇指: 提交</li>
                    <li>剪刀: 重置</li>
                    <li>握紧拳头: 关闭</li>
                </ul>
            </div>
        </div>
    );
};

export default GestureRecognizerComponent;
